<?php

namespace App\Models;

use Carbon\Carbon;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class Admin extends Authenticatable implements JWTSubject
{
    use HasFactory, Notifiable;

    protected $table = 'admins';

    const STATUS_1 = 1;
    const STATUS_2 = 2;

    const STATUS_TEXT = [
        self::STATUS_1 => '<span class="el-tag">正常</span>',
        self::STATUS_2 => '<span class="el-tag el-tag--danger">锁定</span>',
    ];

    protected $fillable = [
        'id','username','nickname','role_id','password','status', 'created_at','updated_at', 'remember_token'
    ];


    protected $hidden = [
        'password', 'remember_token',
    ];


    /**
     * 获取列表
     * @param array $params 条件参数
     * @param array $fields 查询的字段
     * @return mixed
     */
    protected function getList($params = [], $fields = ['*']){
        $lists = $this->select($fields)
            ->where(function ($query) use ($params) {
                if(isset($params['kwd']) && $params['kwd']) {
                    $query ->where('username','like','%' . $params['kwd'] . '%')
                        ->orWhere('nickname','like','%' . $params['kwd'] . '%');
                }
                if(isset($params['status']) && $params['status']) {
                    $query ->where('status',$params['status']);
                }
            })->orderBy('id', 'desc')->paginate(config('app.limit'));
        $this->stateToText($lists,[
            'status' => self::STATUS_TEXT,
        ]);
        return $lists;
    }

    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    /**
     * Return a key value array, containing any custom claims to be added to the JWT.
     *
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return ['role' => 'admin'];
    }

    /**
     * 状态转换
     * @param $data
     * @param array $map
     * @return mixed
     */
    protected function stateToText(&$data, $map = []){
        foreach ($data as $key => &$row) {
            foreach ($map as $col => $pair) {
                if (isset($row[$col]) && isset($pair[$row[$col]])) {
                    $text = $col . '_text';
                    $row[$text] = $pair[$row[$col]];
                }
            }
        }
        return $data;
    }
}
